package com.baohulu.baohulu.utils;

import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class TimeUtil {
    private static final String TAG = "TimeUtil";

    private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @SuppressWarnings("StringBufferReplaceableByString")
    public static String formatTime(long timeInSecond) {
        int totalSecond = (int) timeInSecond;
        int hour = totalSecond / 3600;
        int minute = (totalSecond - hour * 3600) / 60;
        int second = totalSecond - hour * 3600 - minute * 60;
        StringBuilder sb = new StringBuilder();
        sb.append(String.format(Locale.getDefault(), "%02d", hour));
        sb.append(':');
        sb.append(String.format(Locale.getDefault(), "%02d", minute));
        sb.append(':');
        sb.append(String.format(Locale.getDefault(), "%02d", second));
        return sb.toString();
    }

    public static String formatTimeInChinese(long timeInSecond) {
        int totalSecond = (int) timeInSecond;
        int hour = totalSecond / 3600;
        int minute = (totalSecond - hour * 3600) / 60;
        int second = totalSecond - hour * 3600 - minute * 60;
        StringBuilder sb = new StringBuilder();
        if (hour > 0) {
            sb.append(String.format(Locale.getDefault(), "%02d", hour));
            sb.append('时');
        }
        if (minute >= 0) {
            sb.append(String.format(Locale.getDefault(), "%02d", minute));
            sb.append('分');
        }
        if (second >= 0) {
            sb.append(String.format(Locale.getDefault(), "%02d", second));
            sb.append('秒');
        }
        return sb.toString();
    }

    public static long timeInSecond(String time) {
        long timeInSecond = 0;
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());
        try {
            Date date = sdf.parse(time);
            timeInSecond = date.getTime();
        } catch (ParseException e) {
            Log.e(TAG, "timeInSecond: ", e);
            e.printStackTrace();
        }
        return timeInSecond / 1000;
    }
}
